package com.base.common.fragment

import android.app.Activity
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentActivity
import androidx.viewbinding.ViewBinding
import com.base.common.utils.DialogUtil
import com.base.common.viewmodel.BaseViewModel
import com.base.common.widget.LoadingDialog
import dagger.hilt.android.qualifiers.ActivityContext

/**
 * 基类
 */
abstract class BaseFragment<VB : ViewBinding, VM : BaseViewModel> : BasicFragment<VB>() {

    protected abstract val viewModel: VM
    protected var loadingDialog: LoadingDialog? = null
    protected  var mContext: FragmentActivity?=null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        this.lifecycle.addObserver(viewModel)
        this.mContext=activity
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun onDestroy() {
        super.onDestroy()
        this.lifecycle.removeObserver(viewModel)
    }


    open fun showLoading(msg: String?) {
        var msg = msg
        if (TextUtils.isEmpty(msg)) msg = "加载中..."
        if (loadingDialog != null && loadingDialog!!.isShowing
            && TextUtils.equals(loadingDialog!!.message, msg)
        ) {
            return
        }
        if (loadingDialog == null) {
            loadingDialog = DialogUtil.showLoading(mContext, msg)
        } else {
            loadingDialog!!.setType(LoadingDialog.TYPE_LOADING)
            loadingDialog!!.message = msg
            if (!mContext!!.isDestroyed() && !loadingDialog!!.isShowing) {
                loadingDialog!!.show()
            }
        }
    }

    open fun dismissLoading() {
        if (loadingDialog != null && loadingDialog!!.isShowing) {
            loadingDialog!!.dismiss()
        }
    }

//    open fun showToast(msg: String?) {
//        ToastUtil.showToast(msg)
//    }
}